package org.uni_hi.muus.server.util;

import java.util.Enumeration;

import org.uni_hi.muus.util.HTTPUtils;

import lib.java.util.StringTokenizer;


public class Query extends DataContainer {

	protected Query(){
		super("&","=");	
	}
	
	public Query(String q){
		this();
		setQueryString(HTTPUtils.decodeURL(q));
	}
	
	public Query(Query q){
		this();
		setQuery(q);
	}
	
	public void setQuery(Query q){
		this.clear();
		addQuery(q);
	}
	
	public void addQuery(Query q){
		Enumeration e=q.keys();
		Object o=null;
		while(e.hasMoreElements()){
			o=e.nextElement();
			this.put(o, q.get(o));
		}	
	}
	
	protected void addToken(String var){
		String val=null;
		int i=var.indexOf(_valueToken);
		if(i<0){
			val="";
		}else{
			val=var.substring(i+1);
			var=var.substring(0, i).toLowerCase();
		}
		System.out.println("Query var: "+var+" | Query val: "+val);
		this.put(var, val);
	}
	
	public void setQueryString(String q){
		this.clear();
		addQueryString(q);
	}
	
	public void addQueryString(String q){
		/*TODO: before parsing check if string is encoded and if decode it.
		 * 		therefore to create is a new class. btw. look out for some source code
		 * 		might be way easier...
		 */
		StringTokenizer st=new StringTokenizer(q,"&");
		while(st.hasMoreTokens()){
			addToken(st.nextToken());
		}
	}
	
	public String toString(){
		return super.toString();
	}
}